package com.one.blocks.rbac.manager;

import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.one.blocks.mvc.manager.AbstractBatchManager;
import com.one.blocks.rbac.constant.RbacConstant.RoleCache;
import com.one.blocks.rbac.domain.SysRole;
import com.one.blocks.rbac.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;

/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2022-05-01 10:06:14
 */
@Service
public class SysRoleManager extends AbstractBatchManager<SysRoleMapper, SysRole> {

    @Autowired
    private SysRoleManager sysRoleManager;

    @Autowired
    public SysRoleManager(SysRoleMapper mapper) {
        super(mapper);
    }

    @CacheInvalidate(area = RoleCache.AREA, name = RoleCache.ID, key = "#id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(Serializable id) {
        return super.delete(id);
    }

    @CacheInvalidate(area = RoleCache.AREA, name = RoleCache.ID, key = "#entity.id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateById(SysRole entity) {
        return super.updateById(entity);
    }

    @CacheInvalidate(area = RoleCache.AREA, name = RoleCache.ID, key = "#entity.id")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateSelectiveById(SysRole entity) {
        return super.updateSelectiveById(entity);
    }

    @Cached(area = RoleCache.AREA, name = RoleCache.ID, key = "#id", cacheType = CacheType.BOTH)
    @Override
    public SysRole get(Serializable id) {
        return super.get(id);
    }

    @Cached(area = RoleCache.AREA, name = RoleCache.USER_ID, key = "#userId", cacheType = CacheType.BOTH)
    public Integer selectByUserId(Integer userId) {
        return mapper.selectByUserId(userId);
    }

    public SysRole getByUserId(Integer userId) {
        Integer roleId = sysRoleManager.selectByUserId(userId);
        return sysRoleManager.get(roleId);
    }
}